package br.com.hsp.system.beans;

import java.util.List;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;

import br.com.hsp.system.repository.MedicoLabRepository;
import br.com.hsp.users.MedicoLaboratorio;

@ManagedBean
public class MedicoLabBean {

	private MedicoLaboratorio medicoLaboratorio = new MedicoLaboratorio();	
		
	private List<MedicoLaboratorio> medicosLaboratorio; 

	public void add() {
		System.out.println("add");
		EntityManager manager = this.getManager();
		MedicoLabRepository medicoLaboratorioRepository = new MedicoLabRepository(manager);
	
		if (this.medicoLaboratorio.getId() == null) {
			medicoLaboratorioRepository.add(this.medicoLaboratorio);
		} else {
			medicoLaboratorioRepository.atualiza(this.medicoLaboratorio);
		}
		this.medicoLaboratorio = new MedicoLaboratorio();
	}

	public void preparaAlteracao() {
		Map<String, String> params = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestParameterMap();
		Long id = Long.parseLong(params.get("id"));
		EntityManager manager = this.getManager();
		MedicoLabRepository repository = new MedicoLabRepository(manager);
		this.medicoLaboratorio = repository.procura(id);

	}
	

	public void remove() {
		System.out.println("remove");
		Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		Long id = Long.parseLong(params.get("id"));
		EntityManager manager = this.getManager();
		MedicoLabRepository repository = new MedicoLabRepository(manager);
		repository.remove(id);
		this.medicoLaboratorio = null;
		this.medicosLaboratorio = null;
	}
	

	private EntityManager getManager() {
		FacesContext fc = FacesContext.getCurrentInstance();
		ExternalContext ec = fc.getExternalContext();
		HttpServletRequest request = (HttpServletRequest) ec.getRequest();
		return (EntityManager) request.getAttribute("EntityManager");

	}

	public List<MedicoLaboratorio> getMedicosLaboratorio() {
		if (this.medicosLaboratorio == null) {
			EntityManager manager = this.getManager();
			MedicoLabRepository repository = new MedicoLabRepository(manager);
			this.medicosLaboratorio = repository.getLista();
		}
		return this.medicosLaboratorio;
	}

	public MedicoLaboratorio getMedicoLaboratorio() {
		return medicoLaboratorio;
	}

	public void setMedicoLaboratorio(MedicoLaboratorio medicoLaboratorio) {
		this.medicoLaboratorio = medicoLaboratorio;
	}

}
